package ro.gateway.aida.servlet;

import java.io.IOException;
import java.sql.SQLException;
import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Vector;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import ro.gateway.aida.db.PersistenceManager;
import ro.gateway.aida.db.PersistenceToken;
import ro.gateway.aida.obj.Person;
import ro.gateway.aida.obj.db.PersonDB;
import ro.gateway.aida.srv.EditorServlet;
import ro.gateway.aida.srv.ICFService;
import ro.gateway.aida.utils.HttpUtils;



/**
 * PersSelectorServlet
 * @author Mihai Postelnicu <p>
 *  mihai@ro-gateway.org
 */
public class PersSelectorServlet extends EditorServlet

{
      public PersSelectorServlet()
      {
      }
      
      protected void generateCommon( HttpServletRequest request,
                                     ICFService cfService )
      {
			PersistenceToken token = PersistenceManager.tokenLookup( getServletContext() );
            String orgids = HttpUtils.getValidTrimedString( request, "orgids", null );
            HttpSession session = request.getSession();
            Hashtable beans = ( Hashtable ) session.getAttribute( PNAME_BEANS );
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            String action = ( String ) bean.get( PNAME_ACTION );
            String key = ( String ) request.getAttribute( PNAME_KEY );
            String search = HttpUtils.getValidTrimedString( request, "search", null );
            PersonDB persdb = PersonDB.getManager(token);
            String perskey = HttpUtils.getValidTrimedString( request, "perskey", "anonymous" );

            Vector list = ( Vector ) bean.get( PNAME_PERSLIST );

            //displays an explaining message in the jsp:

            String verbose = ( String ) bean.get( PNAME_VERBOSE );
            try
            {
                  if ( "all".equals( orgids ) )
                  {
                        list = persdb.getAll();
                        verbose = "all";
                  }
                  else if ( orgids != null )
                  {
                        list = persdb.getByOrg( orgids );
                        verbose = "byOrg";
                  }
                  if ( list == null )
                  {
                        list = persdb.getUnselected();
                        verbose = "unassigned";
                  }
            }
            catch ( SQLException ex )
            {
                  ex.printStackTrace();
            }

            bean.put( PNAME_VERBOSE, verbose );
            bean.put( PNAME_PERSLIST, list );
            Hashtable persels = ( Hashtable ) beans.get( PNAME_PERSELS );
            if ( persels == null )
            {
                  persels = new Hashtable();
                  beans.put( PNAME_PERSELS, persels );
            }

            bean.put( PNAME_PERSKEY, perskey );
            Vector persel = ( Vector ) bean.get( PNAME_SELECTEDPERS );
            if ( persel == null )
            {
                  //try to revive person selector from session:
                  persel = ( Vector ) persels.get( perskey );
                  if ( persel == null ) persel = new Vector();
                  bean.put( PNAME_SELECTEDPERS, persel );
            }

      }

      protected void edit( HttpServletRequest request, HttpServletResponse response ) throws
            javax.servlet.ServletException, java.io.IOException
      {
            //is this a search refresh ?
            String search = HttpUtils.getValidTrimedString( request, "search", null );
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            String lang = HttpUtils.getValidTrimedString( request, "lang", "ro" );
            ServletContext application = this.getServletContext();
            ICFService cfService = ( ICFService )
                  ( ( Hashtable ) application.getAttribute( Constants.SERVICES ) ).get(
                        Constants.SERVICE_CF );
			PersistenceToken token = PersistenceManager.tokenLookup( application );
            generateCommon( request, cfService );
            if ( search != null )
            {
                  //yes.it is ! refresh the selector
                  Vector list = ( Vector ) bean.get( PNAME_PERSLIST );
                  try
                  {
                        PersonDB persdb = PersonDB.getManager(token);
                        list = persdb.getByLike( search );
                        bean.put( PNAME_PERSLIST, list );
                  }
                  catch ( SQLException ex )
                  {
                        ex.printStackTrace();
                  }

            }
            else
            {

                  //no,it's just an add..
                  long perselect = HttpUtils.getLong( request, "perselect", -1 );
                  //read the selected orgs
                  if ( perselect == -1 )
                  {
                        request.setAttribute( PNAME_SCREEN, PNAME_ERRORS );
                  }
                  else
                  {
                        Vector selected = ( Vector ) bean.get( PNAME_SELECTEDPERS );
                        Vector list = ( Vector ) bean.get( PNAME_PERSLIST );
                        boolean inserted = false;
                        Person pers;
                        for ( Enumeration e = selected.elements(); e.hasMoreElements(); )
                        {
                              pers = ( Person ) e.nextElement();
                              if ( pers.getId() == perselect )
                              {
                                    inserted = true;
                              }
                        }

                        if ( !inserted )
                        { //insert it in the selected list :
                              for ( Enumeration e = list.elements(); e.hasMoreElements(); )
                              {
                                    pers = ( Person ) e.nextElement();
                                    if ( pers.getId() == perselect )
                                    {
                                          selected.add( pers );
                                    }
                              }
                        }
                        bean.put( PNAME_SELECTEDPERS, selected );
                  }
            }

            request.setAttribute( PNAME_SCREEN, PV_SCR_EDIT );
            request.getRequestDispatcher( JSP_PAGE ).
                  forward( request, response );
      }

      protected void other_action_performed( HttpServletRequest request,
                                             HttpServletResponse response,
                                             String action ) throws javax.servlet.
            ServletException, java.io.IOException
      {
      }

      protected void confirm( HttpServletRequest request,
                              HttpServletResponse response ) throws javax.servlet.
            ServletException, java.io.IOException
      {
            //confirm here resets everything :
            ServletContext application = this.getServletContext();
			PersistenceToken token = PersistenceManager.tokenLookup( application );
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            ICFService cfService = ( ICFService )
                  ( ( Hashtable ) application.getAttribute( Constants.SERVICES ) ).get(
                        Constants.SERVICE_CF );
            String param = HttpUtils.getValidTrimedString( request, PNAME_PARAM, null );
            String lang = HttpUtils.getValidTrimedString( request, "lang", "ro" );
            PersonDB orgdb = PersonDB.getManager(token);
            if ( "showall".equals( param ) )
            {
                  Vector list = new Vector();
                  try
                  {
                        list = orgdb.getAll();
                        bean.put( PNAME_VERBOSE, "all" );
                  }
                  catch ( SQLException ex )
                  {
                        ex.printStackTrace();
                  }
                  bean.put( PNAME_PERSLIST, list );
            }
            if ( "clear".equals( param ) )
            {
                  Vector selected = new Vector();
                  bean.put( PNAME_SELECTEDPERS, selected );
            }
            request.setAttribute( PNAME_SCREEN, PV_SCR_EDIT );
            request.getRequestDispatcher( JSP_PAGE ).
                  forward( request, response );
      }

      protected void start_editing(
            ServletContext application,
            HttpServletRequest request,
            HttpServletResponse response ) throws IOException, ServletException
      {
            super.start_editing( application, request, response );

            HttpSession session = request.getSession();
            Hashtable beans = ( Hashtable ) session.getAttribute( PNAME_BEANS );
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            String action = ( String ) bean.get( PNAME_ACTION );
            String key = ( String ) request.getAttribute( PNAME_KEY );
            String search = HttpUtils.getValidTrimedString( request, "search", null );

            //get org list
            ICFService cfService = ( ICFService )
                  ( ( Hashtable ) application.getAttribute( Constants.SERVICES ) ).get(
                        Constants.SERVICE_CF );

            //get the list of org ids :

            generateCommon( request, cfService );

      }

      public String getPNAME_BEANS()
      {
            return PNAME_BEANS;
      }

      protected void cancel(
            HttpServletRequest request,
            HttpServletResponse response ) throws IOException, ServletException
      {
            super.cancel( request, response );
      }

      protected void save( ServletContext application, HttpServletRequest request,
                           HttpServletResponse response ) throws javax.servlet.
            ServletException, java.io.IOException
      {
            Hashtable bean = ( Hashtable ) request.getAttribute( PNAME_BEAN );
            Hashtable beans = ( Hashtable ) request.getSession().getAttribute( PNAME_BEANS );
            Hashtable persels = ( Hashtable ) beans.get( PNAME_PERSELS );

            Vector selected = ( Vector ) bean.get( PNAME_SELECTEDPERS );

            String action = ( String ) bean.get( PNAME_ACTION );
            String perskey = HttpUtils.getValidTrimedString( request, "perskey", null );

            if ( beans == null || selected == null || perskey == null || persels == null )
            {
                  request.setAttribute( PNAME_SCREEN, PV_SCR_ERROR );
                  request.setAttribute( PNAME_ERRORS, "Not a valid PERS Selector Save" );
                  request.getRequestDispatcher( JSP_PAGE ).forward( request, response );
            }

            //put the selected items into the session
            persels.put( perskey, selected );

            request.setAttribute( PNAME_SCREEN, PV_SCR_READY );
            request.getRequestDispatcher( JSP_PAGE ).forward( request, response );
            return;

      }

      public String getJSP_PAGE()
      {
            return JSP_PAGE;
      }

      public static final String PNAME_PARAM = "param";
      public static final String PNAME_VERBOSE = "explanatory text";
      public static final String PV_SCR_READY = "redirect to origin of request";
      public static final String PNAME_PERSKEY = "person select key";
      public static final String PNAME_BEANS = "SELECTING_PERSONS";
      public static final String PNAME_SELECTEDPERS = "PERS already Selected List";
      public static final String PNAME_PERSELS = "PERS Selected Hastable";
      public static final String PNAME_PERSLIST = "PERS selector list by orgType";
      public static final String JSP_PAGE = "persel.jsp";
      public static final String PNAME_ERRORS = "errors";

}
